﻿using System.Collections.Generic;
using DL.Animation;
using DL.Combat.Base.Data;
using DL.Tools;
using Messegers;
using Tools.Unilts;
using UnityEngine;

namespace DL.Combat.Base
{
    public abstract class  CharacterBaseAttackCombatController : CharacterCombatBase
    {
        private Collider[] m_Enemies;
        protected CombatActionSO CurrentCombatAction;

        protected ComboActionConfigSO CurrentComboActionConfig;
        protected List<Transform> CurrentEnemy;

        protected Transform LockTarget;

        protected bool CanAttackInput;
        protected bool CanDetection;
        protected int HitComboIndex;
        
        protected bool CanDrawDetectionRang = true;

        public CharacterBaseAttackCombatController(ComboActionConfigSO comboActionConfig)
        {
            CurrentComboActionConfig = Object.Instantiate(comboActionConfig);
            CurrentComboActionConfig.InitComboConfig();
            m_Enemies = new Collider[5];
            CurrentEnemy = new();
            
            CanAttackInput = true;
            CanDetection = true;
        }

        protected void ChangeComboAction(CombatActionSO config)
        {
            CurrentCombatAction = config;
            ResetHitIndex();
        }

        protected override void TriggerDamaged()
        {
            if (!Animator.CheckAnimationTag(AnimatorTag.Attack)) return;
            if (CurrentEnemy.Count > 0)
            {
                foreach (var enemy in CurrentEnemy)
                {
                    if (UmbrellaAttact(Self, enemy, CurrentCombatAction.AactionAngle[HitComboIndex],
                            CurrentCombatAction.ActionDistance[HitComboIndex]))
                    {
                        //招式表,阶段,攻击者,被打者
                        Messenger<CombatActionSO, int, Transform, Transform>.Broadcast(MessengerName.MSG_HurtEvt,
                            CurrentCombatAction, HitComboIndex, Self, enemy);
                    }
                }
            }
            // CurrentEnemy.Clear();
            UpdateHitIndex();
        }

        /// <summary>
        /// 检测附近范围内的目标
        /// </summary>
        public int DetectionRangEnemy()
        {
            if (CanDetection)
            {
                Debug.Log("检测敌人");
                var count = Physics.OverlapSphereNonAlloc(Self.position + (Self.up * .7f),
                    CurrentComboActionConfig.detectionRang,
                    m_Enemies, CurrentComboActionConfig.enemiesLayer, QueryTriggerInteraction.Ignore);
                return count;
            }
            return -1;
        }

        /// <summary>
        /// 锁定敌人
        /// </summary>
        public Transform TryLockEnemy()
        {
            CurrentEnemy.Clear(); //清除一次伤害列表
            Transform enemy = null;
            float distance = Mathf.Infinity;

            foreach (var e in m_Enemies)
            {
                if (e == null) break;
                var dis = DevelopmentToos.CalculateDistance(Self, e.transform);
                if (dis < distance)
                {
                    CurrentEnemy.Add(e.transform); //添加到可伤害列表
                    enemy = e.transform;
                    distance = dis;
                }
            }

            //指定看向最近的一个敌人
            if (distance <= CurrentComboActionConfig.detectionRang)
            {
                LockTarget =
                    (enemy != null || enemy != LockTarget)
                        ? enemy
                        : LockTarget;
            }
            return LockTarget;
        }

        /// <summary>
        /// 看向敌人
        /// </summary>
        public void TryLookEnemy()
        {
            if (LockTarget == null) return;
            if (DevelopmentToos.CalculateDistance(LockTarget, Self) > 5f) return;
            if (Animator.CheckAnimationTag(AnimatorTag.Attack) && Animator.AnimationNormalTime() < .75f)
            {
                Self.Look(DevelopmentToos.CalculateDirection(LockTarget, Self), 200f);
            }
        }
        
        private void ClearEnemy()
        {

            if (Animator.CheckAnimationTag(AnimatorTag.Hit))
            {
                LockTarget = null;
            }
            
            if (Animator.CheckAnimationTag(AnimatorTag.Dodge))
            {
                LockTarget = null;
            }
        }

        /// <summary>
        /// 更新Combo信息(递增ComboIndex,重置CD，激活攻击输入)
        /// </summary>
        protected virtual void UpdateComboInfo()
        {
            SetAttackInputCommand(true);
        }
        protected void UpdateHitIndex()
        {
            HitComboIndex++;
            //如果更新了招式表，重置一下HitComboIndex
            HitComboIndex = Mathf.Clamp(HitComboIndex, 0, CurrentCombatAction.MaxHitCount - 1);
        }
        
        /// <summary>
        /// 重置HitIndex
        /// </summary>
        protected void ResetHitIndex()
        {
            HitComboIndex = 0;
        }


        /// <summary>
        /// 设置敌人检测开关
        /// </summary>
        /// <param name="enable"></param>
        public void SetEnemyDetectionCommand(bool enable)
        {
            CanDetection = enable;
        }

        /// <summary>
        /// 设置攻击输入是否激活
        /// </summary>
        /// <param name="enable"></param>
        public void SetAttackInputCommand(bool enable)
        {
            CanAttackInput = enable;
        }

        public CombatActionSO GetCurrentCombatAction() => CurrentCombatAction;

        
        public void DrawDetectionRang()
        {
            if (CanDrawDetectionRang)
            {
                Gizmos.color = Color.red;
                Gizmos.DrawWireSphere(Self.position + (Self.up * .7f), CurrentComboActionConfig.detectionRang);
            }
        }

        public void AttackRangeIndicator()
        {
            if (CurrentCombatAction == null) return;
            Gizmos.color = Color.black;
            GizmosTools.DrawWireSemicircle(Self.position + Self.up * .7f, Self.forward,
                CurrentCombatAction.ActionDistance[HitComboIndex],
                (int)CurrentCombatAction.AactionAngle[HitComboIndex]);
        }
    }
}